package com.besttone.search;

import com.besttone.app.SuggestionProvider;
import com.besttone.http.UpdateRequest;
import com.besttone.http.UpdateRequest.UpdateListener;
import com.besttone.search.Client.GetLocationAdressListener;
import com.besttone.search.R.color;
import com.besttone.search.dialog.ProgressBarDialog;
import com.besttone.search.model.City;
import com.besttone.search.sql.NativeDBHelper;
import com.besttone.search.util.LogUtils;
import com.besttone.search.util.SharedUtils;
import com.besttone.widget.scroll.MyScrollLayout;
import com.besttone.widget.scroll.OnViewChangeListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity
{
	private GridView grid;
	private DisplayMetrics localDisplayMetrics;
	private View mainView;
	private View swithViewContainer;
	private Button btn_city_search;
	private Button mSearchBtn;
	private SearchRecentSuggestions suggestions;
	
	private City lastLocationCity;
	
	private MyScrollLayout mScrollLayout;
	private ImageView[] mImageViews;
	private int mViewCount;
	private int mCurSel;
	
	private final boolean bMultiTag = false;
		
	public void onCreate(Bundle bundle)
	{
		super.onCreate(bundle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);		

		if(bMultiTag)
		{
			swithViewContainer = this.getLayoutInflater().inflate(R.layout.switch_view, null);
			setContentView(R.layout.switch_view);
			initChildView();
		}
		else
		{
			mainView = this.getLayoutInflater().inflate(R.layout.main, null);
			setContentView(mainView);
			initMainView();
		}
				
		detectUpdate();
	}
	
	private void initMainView()
	{
		btn_city_search = (Button) mainView.findViewById(R.id.btn_city);
		btn_city_search.setOnClickListener(searchCityListner);
		
		String str = null;
		String cityName = (String) this.btn_city_search.getText();
		SharedPreferences sharedPreferences = this.getSharedPreferences("Location_City_Data", 0);
		str=sharedPreferences.getString("Location_City", "上海");
		
		Log.d("main", "new city:" + str);
		Log.d("main", "old city:" + cityName);
		this.btn_city_search.setText(str);
		
	    mSearchBtn = ((Button)mainView.findViewById(R.id.start_search));
	    mSearchBtn.setOnClickListener(searchHistroyListner);

		localDisplayMetrics = getResources().getDisplayMetrics();
		
		suggestions = new SearchRecentSuggestions(this,
				SuggestionProvider.AUTHORITY, SuggestionProvider.MODE);
		
		grid = (GridView)mainView.findViewById(R.id.my_grid);
		ListAdapter adapter = new GridAdapter(this);
		grid.setAdapter(adapter);
		grid.setOnItemClickListener(mOnClickListener);	
	}
	
//------------------------------ 多tag切换  ---------------------------------
	private void initChildView()
	{
		LinearLayout linearLayout = (LinearLayout) findViewById(R.id.llayout);
		mScrollLayout = (MyScrollLayout)findViewById(R.id.mScrollLayout);

		mainView = this.getLayoutInflater().inflate(R.layout.main, mScrollLayout);	
		initMainView();
//		mScrollLayout.addView(mainView);

		View child = new ImageView(this);
		mScrollLayout.addView(child);

		mViewCount = mScrollLayout.getChildCount();
		mImageViews = new ImageView[mViewCount];

		for (int i = 0; i < mViewCount; i++)
		{
			mImageViews[i] = (ImageView) linearLayout.getChildAt(i);
			mImageViews[i].setEnabled(true);
			mImageViews[i].setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					int pos = (Integer) (v.getTag());
					setCurPoint(pos);
					mScrollLayout.snapToScreen(pos);
				}
			});
			
			mImageViews[i].setTag(i);
		}

		mCurSel = 0;
		mImageViews[mCurSel].setEnabled(false);

		mScrollLayout.SetOnViewChangeListener(new OnViewChangeListener()
		{

			@Override
			public void OnViewChange(int view)
			{
				// TODO Auto-generated method stub
				setCurPoint(view);
			}
		});
	}

	private void setCurPoint(int index)
	{
		if (index < 0 || index > mViewCount - 1 || mCurSel == index)
		{
			return;
		}

		mImageViews[mCurSel].setEnabled(true);
		// if(index!=mViewCount - 1)
		// mImageViews[index].setEnabled(true);
		// else
		mImageViews[index].setEnabled(false);

		mCurSel = index;
	}


//-----------------------------------------------------------------
	
	private void updateLocaton()
	{
		Client.getInstance().setmLoactionDlistener(new GetLocationAdressListener()
		{
			
			@Override
			public void onGetLocationAdress()
			{
				// TODO Auto-generated method stub
				try
				{
					String curCityName=SharedUtils.getCurrentCityName(Client.getContext());
					lastLocationCity=SharedUtils.selectCity();
					String lastLocationCityName=lastLocationCity.getCityName();
					if(!curCityName.equals("")&&!curCityName.equals(lastLocationCityName))
					{
						Client.postRunnable(new Runnable()
						{
							
							@Override
							public void run()
							{
								// TODO Auto-generated method stub
								
								if(Client.getInstance().bChangeCity)
									openAlertChangeCityDialog();
							}
						});
					}
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onFialedGetLocationAdress()
			{
				// TODO Auto-generated method stub
				Client.postRunnable(new Runnable()
				{
					
					@Override
					public void run()
					{
						// TODO Auto-generated method stub

						Toast.makeText(Client.getContext(), "请检查网络连接！", Toast.LENGTH_SHORT);
					}
				});
			}
		});
		
		Client.getInstance().enableMyLocation();
//		Thread t=new Thread(new Runnable()
//		{
//			
//			@Override
//			public void run()
//			{
//				// TODO Auto-generated method stub
//				do
//				{
//					try
//					{
//						Thread.sleep(60000);
//					}
//					catch (InterruptedException e)
//					{
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					Client.getInstance().enableMyLocation();
//				}
//				while (true);
//			}
//		});
//		t.start();
	}	
	
	private void openAlertChangeCityDialog()
	{
		Client.getInstance().disableMyLocation();
		String str=getString(R.string.change_city_by_location).replace("[]", SharedUtils.getLastLocationCity().getCityName());
		new AlertDialog.Builder(MainActivity.this).setTitle(R.string.prompt)
				.setMessage(str)
				.setCancelable(false)
				.setPositiveButton(R.string.switch_text, new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialoginterface, int i)
					{

						SharedUtils.setCurrentCity(Client.getContext(), lastLocationCity);
						btn_city_search.setText(lastLocationCity.getCityName());
//						Client.getInstance().enableMyLocation();
					}
				}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialoginterface, int i)
					{
						Client.getInstance().bChangeCity = false;
//						Client.getInstance().enableMyLocation();
					}
				}).show();
	}
    
    private Button.OnClickListener searchHistroyListner = new Button.OnClickListener() {
    	public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, SearchActivity.class);
			startActivity(intent);
    	}
    };
    
    private Button.OnClickListener searchCityListner = new Button.OnClickListener() {
    	public void onClick(View v) {
			Intent intent = new Intent();
			intent.setClass(MainActivity.this, SelectCityActivity.class);
			intent.putExtra("SelectCityName", btn_city_search.getText().toString());
			startActivityForResult(intent, 100);
		}
    };
    
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		LogUtils.i("resultCode:" + resultCode + ", requestCode:" + requestCode);
		String str = null;
		String cityName = (String) this.btn_city_search.getText();
		if (resultCode == RESULT_OK) {
			str = data.getStringExtra("cityName");
			LogUtils.d(LogUtils.LOG_TAG, "new city:" + str);
			LogUtils.d(LogUtils.LOG_TAG, "old city:" + cityName);
			super.onActivityResult(requestCode, resultCode, data);
			this.btn_city_search.setText(str);
		}
	}
	
	private AdapterView.OnItemClickListener mOnClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
			TextView text = (TextView)v.findViewById(R.id.activity_name);
			String keyword = text.getText().toString();
			Intent intent = new Intent();
			if (keyword != null) {
				if ("更多".equals(keyword)) {
					intent.setClass(MainActivity.this, MoreKeywordActivity.class);
					startActivity(intent);
				} else {
					intent.setClass(MainActivity.this, SearchResultActivity.class);
					Bundle bundle = new Bundle();
		    		bundle.putString("keyword", keyword);
		    		intent.putExtras(bundle);
		    		
		    		suggestions.saveRecentQuery(keyword, null);
		    		
		    		startActivity(intent);
				}
			}
		}
	};
	
	public class GridAdapter extends BaseAdapter 
	{
		private LayoutInflater inflater;
		
		public GridAdapter(Context context) 
		{
			inflater = LayoutInflater.from(context);
		}

		public final int getCount() 
		{
			return 6;
		}

		public final Object getItem(int paramInt) 
		{
			return null;
		}

		public final long getItemId(int paramInt) 
		{
			return paramInt;
		}

		public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) 
		{
			paramView = inflater.inflate(R.layout.activity_label_item, null);
			TextView text = (TextView)paramView.findViewById(R.id.activity_name);
			text.setTextSize(15);
			text.setTextColor(color.text_color_grey);
			
			switch(paramInt)
			{
				case 0:
				{
					text.setText("KTV");
					Drawable draw = getResources().getDrawable(R.drawable.ktv);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 1:
				{
					text.setText("宾馆");	
					Drawable draw = getResources().getDrawable(R.drawable.hotel);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 2:
				{
					text.setText("加油站");	
					Drawable draw = getResources().getDrawable(R.drawable.gas);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 3:
				{
					text.setText("川菜");	
					Drawable draw = getResources().getDrawable(R.drawable.chuan);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 4:
				{
					text.setText("快递");	
					Drawable draw = getResources().getDrawable(R.drawable.kuaidi);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
				case 5:
				{
					text.setText("更多");	
					Drawable draw = getResources().getDrawable(R.drawable.more);
					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
					text.setCompoundDrawables(null, draw, null, null);
					break;
				}
				
//				case 6:
//				{
//					text.setText("最近浏览");	
//					Drawable draw = getResources().getDrawable(R.drawable.home_button_history);
//					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
//					text.setCompoundDrawables(null, draw, null, null);
//					break;
//				}
//				
//				case 7:
//				{
//					text.setText("个人中心");	
//					Drawable draw = getResources().getDrawable(R.drawable.home_button_myzone);
//					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
//					text.setCompoundDrawables(null, draw, null, null);
//					break;
//				}
//				case 8:
//				{
//					text.setText("更多");	
//					Drawable draw = getResources().getDrawable(R.drawable.home_button_more);
//					draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight());
//					text.setCompoundDrawables(null, draw, null, null);
//					break;
//				}
			}

			paramView.setMinimumHeight((int)(96.0F * localDisplayMetrics.density));
			paramView.setMinimumWidth(((-12 + localDisplayMetrics.widthPixels) / 3));
			
			return paramView;
		}
	}
	
    protected static final int MENU_ABOUT = Menu.FIRST;
    protected static final int MENU_Quit = Menu.FIRST+1;
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_ABOUT, 0, " 关于 ...");
		menu.add(0, MENU_Quit, 0, " 结束 ");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case MENU_ABOUT:
			openOptionsDialog();
			break;
		case MENU_Quit:
			showExitAlert();
			break;
		}
		return true;
		}
	
	private void openOptionsDialog() { 
		new AlertDialog.Builder(MainActivity.this)
		.setTitle(R.string.about_title)
		.setMessage(R.string.about_msg)
		.setPositiveButton(R.string.confirm,
				new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {}
				})
		.setNegativeButton(R.string.homepage_label,
				new DialogInterface.OnClickListener(){
						public void onClick(DialogInterface dialoginterface, int i){
							//go to url
							Uri uri = Uri.parse(getString(R.string.homepage_uri));
							Intent intent = new Intent(Intent.ACTION_VIEW, uri);
							startActivity(intent);
						}
				})
		   .show();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 按下键盘上返回按钮
		if(keyCode == KeyEvent.KEYCODE_BACK ){
			showExitAlert();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
	
	private void showExitAlert() {
        new AlertDialog.Builder(this)
        .setTitle(R.string.prompt)
        .setMessage(R.string.quit_desc)
        .setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {}
                })
        .setPositiveButton(R.string.confirm,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                    	exitApp();
                    }
                }).show();
	}
	
	//彻底关闭程序
	protected void exitApp() {
	    super.onDestroy();
	    Client.release();
	    System.exit(0);
	    // 或者下面这种方式
	    // android.os.Process.killProcess(android.os.Process.myPid());
	}

	//检测更新
	protected UpdateRequest r;	
	private void detectUpdate() {
    	r = new UpdateRequest();
		r.setListener(new UpdateListener() {
			@Override
			public void onUpdateNoNeed(String msg) {
				gotoLogin();
			}
			
			public void onUpdateMust(final String msg, final String url) {
				Client.postRunnable(new Runnable()
				{
					
					@Override
					public void run()
					{
						// TODO Auto-generated method stub
						AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
						b.setTitle("程序必须升级才能继续");
						b.setMessage(msg+"\r\n"+url);
						b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
								System.gc();
							}
						});
						b.setPositiveButton("升级",new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								gotoUpdate(url);
							}
						});
						b.setCancelable(false);
						b.show();
					}
				});				
				
				
			}
			
			public void onUpdateError(short code, Exception e) {
				Client.postRunnable(new Runnable()
				{
					
					@Override
					public void run()
					{
						// TODO Auto-generated method stub
						AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
						b.setTitle("升级验证失败");
						b.setMessage("请检查网络...");
						b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
								System.gc();
							}
						});
						b.setCancelable(false);
						b.show();
					}
				});
				
			}
			
			public void onUpdateAvaiable(final String msg, final String url) {
				Client.postRunnable(new Runnable()
				{
					
					@Override
					public void run()
					{
						// TODO Auto-generated method stub
						AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this);
						b.setTitle(R.string.update_title);
						b.setMessage(msg+"\r\n"+url);
						b.setPositiveButton("现在升级",new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								gotoUpdate(url);
							}
						});
						b.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								gotoLogin();
							}
						});
						b.setCancelable(false);
						b.show();
					}
				});
				
			}
		});
		
		if (Client.decetNetworkOn())
		{
//			Log.d("check","on");
			r.checkUpdate();
		}
		else {
//			Log.d("check","off");
			gotoLogin();
			Toast.makeText(MainActivity.this, "网络异常，没有可用网络",
					Toast.LENGTH_SHORT).show();
		}
		
	}
	
	private void gotoLogin() {	
		updateLocaton();
//		getLoacation();			
	}
	
    private void gotoUpdate(String url) {

		if (TextUtils.isEmpty(url)) {
    		Toast.makeText(this, "升级的地址有误", Toast.LENGTH_SHORT).show();
    		finish();
    		System.gc();
    		return;
    	}
//		url = url.toLowerCase();
		if (url.startsWith("www")) {
			url = "http://" + url;
		}
		if (url.startsWith("http")) {
	    	try {
//	    		Uri u = Uri.parse(url);
	    		ProgressBarDialog pbd=new ProgressBarDialog(MainActivity.this);
	    		pbd.setTitle("下载中");
	    		pbd.setOnCancelListener(new OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						// TODO Auto-generated method stub
						gotoLogin();
					}
				});
	    		pbd.show();
	    		pbd.downLoadFile(url);
//	    		Intent i = new Intent( Intent.ACTION_VIEW, u );
//	    		startActivity( i );
//	    		finish();
	    		System.gc();
	    	} catch(Exception e) {
	    		e.printStackTrace();
	    	}
		}
	}
}
